import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {GoodsAddService} from '../goods-add.service';
import {LocalStorageService} from '../../../../lib/service/local-storage.service';
import {AdOssUploadService} from '../../../../lib/service/ad-oss-upload.service';
import {EditorComponent} from '../../../../comm-components/wangeditor/editor.component';
import {appletLimit} from '../../../../../config/api';

@Component({
  selector: 'app-add-manage',
  templateUrl: 'add.component.html',
  styleUrls: ['add.component.scss'],
  providers: [GoodsAddService]
})
export class AddComponent implements OnInit {

  isbn_limit = false;

  codeHelp;
  picHelp;
  otherPicHelp;
  addGroup;
  addType;
  type;
  message;
  isShow;

  // 自定义规格
  custom = false;
  custom_name;
  custom_val;
  custom_vals = [];
  new_custom = [];
  modified_custom = false;
  change_custom_name;
  change_custom_val;
  change_custom_vals = [];
  change_custom_index;

  categoryId; // 当前所选最小分类id
  goodsCategory; // 分类
  goodsAttribute; // 属性集
  appletGoodsCategory; // 分组列表
  appletGoodsCategoryName; // 要添加的分组名称
  appletGoodsCategoryNameStatus = false; // 要添加分组的状态设置

  nowGoodsAttribute; // 当前选中的属性集
  customize;
  stock = []; // sku stock

  expressTemplateList = [];
  provinceList = [];
  cityList = [];
  regionList = [];

  name;
  price; // 销售价格,千分位 微信价
  retail_Price; // 门市价格,千分位 原价
  in_stock; // 库存
  is_tc = false; // 是否套餐选择项
  goods_number; // 产品编号
  weight;

  first_picture_file;
  // first_picture;
  second_picture_file;
  // second_picture;
  third_picture_file;
  // third_picture;
  fourth_picture_file;
  // fourth_picture;

  limited = false;
  max_buy = 0; // 限购数量,0不限购
  is_free_postage = '包邮'; // 是否包邮 enum('包邮', '不包邮')
  goods_at_province = '';
  goods_at_city = '';
  goods_at_district = '';

  express_template_id; // 关联的运费模板ID
  had_invoice = '无'; // 有无发票 enum('无', '有')
  had_warranty_fix = '无'; // 有无保修 enum('无', '有')
  status = '下架'; // enum('上架', '下架')

  description = '';

  // 文件内容
  f = ['', '', '', ''];
  f_file = ['', '', '', ''];
  // 文件名
  f1 = ['first_picture', 'second_picture', 'third_picture', 'fourth_picture'];
  // 文件后缀
  f1_suffix = ['', '', '', ''];

  addStatus = true;
  norm_mode = '无规格';

  @ViewChild(EditorComponent) editor: EditorComponent;

  constructor(private localStorageService: LocalStorageService,
              private router: Router,
              private route: ActivatedRoute,
              private goodsAddService: GoodsAddService,
              private adOssUploadService: AdOssUploadService) {
  }

  ngOnInit() {
    // 判断是否需要显示套餐选择项
    let applet_uuid = this.localStorageService.getNowApplet().applet_uuid;
    appletLimit.every((val, idx, array) => {
      if (val == applet_uuid) {
        this.isbn_limit = true;
        return false;
      } else {
        return true;
      }
    });

    this.editor.changedEitorUsePlace('goods');
    // 获取最小分类，不存在则跳转选择分类
    this.route.queryParams.forEach((params: any) => {
      if (params['category']) {
        this.categoryId = params['category'];
        this.getCategoryParent();
      } else {
        this.router.navigate(['/main/goods-add']);
      }
    });
    this.editor.changedEitorUsePlace('goods');

    this.getAppletGoodsCategory();

    this.getExpressTemplateList();

    this.getProvinceList();

    this.getCustomSku();
  }

  selectImg($event: any, pic_number) {

    // const files = $event.target.files || $event.dataTransfer.files;
    if ($event.path[0].files[0]) {
      const file = $event.path[0].files[0];

      this.f_file[pic_number] = file;

      switch (pic_number) {
        case 0:
          this.first_picture_file = file;
          break;
        case 1:
          this.second_picture_file = file;
          break;
        case 2:
          this.third_picture_file = file;
          break;
        case 3:
          this.fourth_picture_file = file;
          break;
      }


      const myReader = new FileReader();
      const self = this;
      this.f1_suffix[pic_number] = file.name.replace(/.+\./, '').toLowerCase();

      myReader.readAsDataURL(file);
      myReader.onloadend = function (e) {
        self.f[pic_number] = myReader.result;
      };
    } else {
      this.f[pic_number] = '';
      this.f_file[pic_number] = '';
    }
  }

  uploadImg(product_id) {
    const member_id = this.localStorageService.getNowApplet().user_id;
    const applet_id = this.localStorageService.getNowApplet().id;
    this.adOssUploadService
      .getSignature(`/v1/member/detail/${member_id}/${applet_id}/${product_id}?callback=true`)
      .subscribe(
        res1 => {

          this.f_file.every((val, idx, array) => {
            if (val) {
              this.adOssUploadService.fileUpload(val, res1.data, this.f1[idx] + '.' + this.f1_suffix[idx], this.f1[idx])
                .subscribe(res2 => {
                    /*if (res2.status === 200) {
                     this.type = 'success';
                     this.message = '保存成功';
                     this.isShow = true;
                     this.localStorageService.setNowApplet(res.data);
                     if (!!turnPage) {
                     this.router.navigate([`/main/store-product/goods-add`]);
                     }
                     } else {
                     this.type = 'error';
                     this.message = '图片上传失败';
                     this.isShow = true;
                     }*/
                  }
                );
            }
            return true;
          });
          this.addStatus = true;
          this.router.navigate(['/main/store-product/goods-add/success']);
        }
      );
  }

  // 单选
  changeGoodsAttributeOnly($event, item) {
    const value = Number($event.target.value);
    item.attribute_value.every((val, idx, array) => {
      if (val.id === value) {
        val.bind = true;
      } else {
        val.bind = false;
      }
      return true;
    });
  }

  addGoods() {
    this.addStatus = false;
    this.description = this.editor.clickHandle();
    if (this.norm_mode == '无规格') {
      if (this.is_tc) {
        this.goods_number += '@tc@';
      }
    } else {
      this.is_tc = false;
      this.stock.every((val, idx, array) => {
        if(val.is_tc) {
          val.isbn +='@tc@';
        }
        return true;
      });
    }
    this.goodsAddService.addGoods(
      this.localStorageService.getNowApplet().applet_uuid,
      this.categoryId, // 分类id
      this.appletGoodsCategory, // 分组
      this.name, // 商品名称
      this.goodsAttribute,
      this.stock,
      this.price,
      this.retail_Price,
      this.in_stock,
      this.goods_number,
      this.weight,
      // this.first_picture,
      // this.second_picture,
      // this.third_picture,
      // this.fourth_picture,
      this.max_buy,
      this.is_free_postage,
      this.goods_at_province,
      this.goods_at_city,
      this.goods_at_district,
      this.express_template_id,
      this.had_invoice,
      this.had_warranty_fix,
      this.status,
      this.description,
      this.norm_mode,
      this.is_tc
    ).subscribe(res => {

      if (res.code === 2000) {
        if (res.data.id) {
          this.uploadImg(res.data.id);
        }
      } else {
        this.type = 'error';
        this.message = res.message;
        this.isShow = true;
      }

      this.addStatus = true;
    });
  }

  delSku(item) {
    item.selected = false;
    this.doDataMakeTable();
  }

  delCustomSku(item) {
    item.selected = false;
    item.custom_goods_attribute_value.every((val, idx, array) => {
      val.bind = false;
      return true;
    });
    this.doDataMakeTable();
  }

  select_max_buy() {
    if (this.limited === false) {
      this.max_buy = 0;
    } else {
      this.max_buy = null;
    }
  }

  // 根据最小分类id查询到顶级
  getCategoryParent() {
    this.goodsAddService.getCategoryParentById(this.categoryId).subscribe(res => {
      // 分类所属，一维
      this.goodsCategory = res.data.data;
      // 该分类所绑定的 商品集(属性＝＞属性名)
      this.goodsAttribute = res.data.goods_attribute;
      this.goodsAttribute.every((val, idx, array) => {
        // 去除要组合的数据
        val.attribute_value.every((val1, idx1, array1) => {
          val1.goods_attribute_name = val.name;
          return true;
        });

        return true;
      });
    });
  }

  // 获取分组
  getAppletGoodsCategory() {
    this.goodsAddService.getAppletGoodsCategory(this.localStorageService.getNowApplet().applet_uuid).subscribe(res => {
      this.appletGoodsCategory = res.data.data;
    });
  }

  // 添加分组
  addAppletGoodsCategory() {
    this.appletGoodsCategoryNameStatus = true;
    const applet_uuid = this.localStorageService.getNowApplet().applet_uuid;
    if (this.appletGoodsCategoryName) {
      this.goodsAddService.addAppletGoodsCategory(this.appletGoodsCategoryName, applet_uuid).subscribe(
        rs => {
          if (rs.code === 2000) {
            this.appletGoodsCategoryName = null;
            this.getAppletGoodsCategory();
          }
          this.appletGoodsCategoryNameStatus = false;
          // re get
        }
      );
    }
  }

  // 选择属性名
  selectGoodsAttribute($event) {
    const goods_attribute_set_id = Number($event.target.value);
    if (goods_attribute_set_id === 0) {
      this.nowGoodsAttribute = null;
    }
    this.goodsAttribute.every((val, idx, array) => {
      if (val.goods_attribute_set_id === goods_attribute_set_id) {
        this.nowGoodsAttribute = val;
        // val.selected = true;
      }
      return true;
    });
  }


  /*selectGoodsAttributeValue($event) {
   const id = Number($event.target.value);
   if (id === 0) {
   this.nowGoodsAttributeValueId = null;
   } else {
   this.nowGoodsAttributeValueId = id;
   }
   console.log(id);
   }*/

  addGoodsAttribute() {
    this.goodsAttribute.every((val, idx, array) => {
      if (val.goods_attribute_set_id === this.nowGoodsAttribute.goods_attribute_set_id) {
        val.selected = true;
        val.remark = this.customize;
      }
      if (val.attribute_value.length <= 0) {
        val.selected = false;
      } else {
        let c = 0;
        val.attribute_value.every((val1, idx1, array1) => {
          if (val1.bind === true) {
            // val1.goods_attribute_set_id = val.goods_attribute_set_id;
            c++;
          }
          return true;
        });
        if (c === 0) {
          val.selected = false;
        }
      }

      return true;
    });
    this.doDataMakeTable();
  }

  changeGoodsAttribute() {
    this.goodsAttribute.every((val, idx, array) => {
      if (val.attribute_value.length <= 0) {
        val.selected = false;
      } else {
        let c = 0;
        val.attribute_value.every((val1, idx1, array1) => {
          if (val1.bind === true) {
            c++;
          }
          return true;
        });
        if (c === 0) {
          val.selected = false;
        }
      }
      return true;
    });
    this.doDataMakeTable();
  }

  changeCustomAttr() {
    this.new_custom.every((val, idx, array) => {
      let c = 0;
      val.custom_goods_attribute_value.every((val1, idx1, array1) => {
        if (val1.bind === true) {
          val1.goods_attribute_name = val.name;
          val1.goods_attribute_set_remark = val.name;
          val1.is_private = true;
          c++;
        }
        return true;
      });
      if (c === 0) {
        val.selected = false;
      } else {
        val.selected = true;
      }
      return true;
    });
    this.doDataMakeTable();
  }

  // 处理
  doDataMakeTable() {
    const data = [];
    this.goodsAttribute.every((val, idx, array) => {
      // 去除要组合的数据
      if (val.selected === true) {
        const attribute_value_array = [];
        val.attribute_value.every((val1, idx1, array1) => {
          if (val1.bind === true) {
            val1.goods_attribute_set_id = val.goods_attribute_set_id;
            val1.goods_attribute_set_remark = val.remark;
            // val1.goods_attribute_set_attribute_id = val.id;
            attribute_value_array.push(val1);
          }
          return true;
        });
        data.push(attribute_value_array);
      }
      return true;
    });

    this.new_custom.every((val, idx, array) => {
      if (val.selected === true) {
        const attribute_value_array = [];
        val.custom_goods_attribute_value.every((val1, idx1, array1) => {
          if (val1.bind === true) {
            val1.goods_attribute_set_id = val1.custom_goods_attribute_id;
            val1.goods_attribute_id = val.id;
            // val1.goods_attribute_set_remark = val.value;
            // val1.goods_attribute_set_attribute_id = val.id;
            attribute_value_array.push(val1);
          }
          return true;
        });
        data.push(attribute_value_array);
      }
      return true;
    });

    const stock = this.doExchange(data);

    if (stock) {
      this.stock = [];
      stock.every((val, idx, array) => {
        this.stock[idx] = {sku: []};
        // this.stock[idx].sku = [];
        if (val.id) {
          this.stock[idx].sku.push(val);
        } else {
          this.stock[idx].sku = val;
        }
        this.stock[idx]["is_tc"] = false;
        /*this.stock[idx].price = null;
        this.stock[idx].retail_Price = null;
        this.stock[idx].in_stock = null;
        this.stock[idx].isbn = null;*/
        return true;
      });
    } else {
      this.stock = [];
    }
  }

  // 组合
  doExchange(arr) {
    const len = arr.length;
    // 当数组大于等于2个的时候
    if (len >= 2) {
      // 第一个数组的长度
      const len1 = arr[0].length;
      // 第二个数组的长度
      const len2 = arr[1].length;
      // 2个数组产生的组合数
      const lenBoth = len1 * len2;
      //  申明一个新数组
      const items = new Array(lenBoth);
      // 申明新数组的索引
      let index = 0;
      for (let i = 0; i < len1; i++) {
        for (let j = 0; j < len2; j++) {
          if (arr[0][i] instanceof Array) {
            items[index] = arr[0][i].concat(arr[1][j]);
          } else {
            items[index] = [arr[0][i]].concat(arr[1][j]);
          }
          index++;
        }
      }
      const newArr = new Array(len - 1);
      for (let i = 2; i < arr.length; i++) {
        newArr[i - 1] = arr[i];
      }
      newArr[0] = items;
      return this.doExchange(newArr);
    } else {
      return arr[0];
    }
  }

  getExpressTemplateList() {
    this.goodsAddService.getExpressTemplateList(this.localStorageService.getNowApplet().applet_uuid).subscribe(res => {
      this.expressTemplateList = res.data.data;
    });
  }

  selectExpressTemplate($event) {
    this.express_template_id = $event.target.value;
  }

  getProvinceList() {
    this.provinceList = [];
    this.cityList = [];
    this.regionList = [];
    this.goodsAddService.getProvinceList().subscribe(res => {
      if (res.data) {
        this.provinceList = res.data;
      }
    });
  }

  selectProvince($event) {
    this.cityList = [];
    this.regionList = [];
    const province_id = $event.target.value;
    if (!province_id) {
      return;
    }
    this.goodsAddService.getCityList(province_id).subscribe(res => {
      if (res.data) {
        this.cityList = res.data;
      }
    });
  }

  selectCity($event) {
    this.regionList = [];
    const city_id = $event.target.value;
    if (!city_id) {
      return;
    }
    this.goodsAddService.getRegionList(city_id).subscribe(res => {
      if (res.data) {
        this.regionList = res.data;
      }
    });
  }

  /*closeModal() {
   }


   /!*自定义添加
   1: 品牌
   *!/
   addItem(type: number) {
   switch (type) {
   case 1:
   if (this.brand == -1) {
   this.addAttr = 2;
   }
   break;
   }
   }

   // 确认添加自定义
   confirmAddItem() {
   this.isShow = true;
   this.message = '添加品牌类目成功';
   }

   promptIsShow(event: any): void {
   this.isShow = event;
   }*/
  promptIsShow(event: any): void {
    this.isShow = event;
  }

  // wangEdit编辑器
  PostData(event): void {
    // console.log(event);
  }

  // 自定义规格
  addCustomValue() {
    this.custom_vals.push(this.custom_val);
    this.custom_val = '';
  }

  addChangeCustomValue() {
    this.change_custom_vals.push(this.change_custom_val);
    this.change_custom_val = '';
  }

  bindGoodsCategory() {
    this.goodsAddService.bindGoodsCategory(this.categoryId, this.custom_name, this.custom_vals).subscribe(res => {
      if (res.code === 2000) {
        this.type = 'success';
        this.isShow = true;
        this.message = '成功添加自定义规格';
        this.custom_name = '';
        this.custom_val = '';
        this.custom_vals = [];
        res.data.selected = true;
        res.data.custom_goods_attribute_value.every((val, idx, array) => {
          val.bind = true;
          val.goods_attribute_name = res.data.name;
          val.goods_attribute_set_remark = res.data.name;
          val.is_private = true;
          return true;
        });
        this.new_custom.push(res.data);
        this.doDataMakeTable();
      } else {
        this.type = 'error';
        this.isShow = true;
        this.message = res.message;
      }
    });
  }
  changeBindGoodsCategory() {
    if (!!this.change_custom_vals.length) {
      this.goodsAddService.bindGoodsCategory(this.categoryId, this.change_custom_name, this.change_custom_vals).subscribe(res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.isShow = true;
          this.message = '成功修改自定义规格';
          this.new_custom.splice(this.change_custom_index,1);
          this.modified_custom = false;
          res.data.selected = true;
          res.data.custom_goods_attribute_value.every((val, idx, array) => {
            val.bind = true;
            return true;
          });
          this.new_custom.push(res.data);
          this.doDataMakeTable();
        } else {
          this.type = 'error';
          this.isShow = true;
          this.message = res.message;
        }
      })
    } else {
      this.goodsAddService.delCustomSku(this.new_custom[this.change_custom_index].id).subscribe(res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.isShow = true;
          this.message = '成功修改自定义规格';
          this.new_custom.splice(this.change_custom_index,1);
          this.modified_custom = false;
          this.doDataMakeTable();
        } else {
          this.type = 'error';
          this.isShow = true;
          this.message = res.message;
        }
      })
    }

  }

  getCustomSku() {
    this.goodsAddService.getCustomSku(this.categoryId).subscribe(res => {
      this.new_custom = res.data;
    });
  }

  modifyCustom(item, i) {
    console.log(i);
    this.modified_custom = true;
    this.change_custom_name = item.name;
    this.change_custom_vals = [];
    this.change_custom_index = i;
    item.custom_goods_attribute_value.every((val, idx, array) => {
      this.change_custom_vals.push(val.value);
      return true;
    });
  }
}
